package test;

import java.io.*;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 马拉圈
 * Date: 2023-04-08
 * Time: 0:55
 */
public class Demo {

    public static void scan(File file, String words) throws IOException {
        File[] files = file.listFiles();
        if(files == null) { // 这里空目录对应的并不是空数组！是null~
            return;
        }else {
            for (int i = 0; i < files.length; i++) {
                File f = files[i];
                if(f.isFile()) {
                    String content = readAll(f);
                    if(content.contains(words)) {
                        System.out.println(f.getCanonicalFile());
                    }
                }
                if(f.isDirectory()) {
                    scan(f, words);
                }
                //两种都不是，就不能读~
            }
        }

    }


    public static String readAll(File f) {
        StringBuilder stringBuilder = new StringBuilder();
        try (Reader reader = new FileReader(f)){
            while(true) {
                int c = reader.read();
                if(c == -1) {
                    break;
                }
                stringBuilder.append((char)c);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return stringBuilder.toString();
    }


    public static void main(String[] args) throws IOException {
        Scanner scanner = new Scanner(System.in);
        System.out.print("请输入要扫描的根目录：");
        String root = scanner.next();
        File file = new File(root);
        if(!file.isDirectory()) { // 1. 目录不存在 2. 不是目录
            System.out.println("输入错误");
            return;
        }
        System.out.print("请输入要查询的词:>");
        String words = scanner.next();

        scan(file, words);//扫描

    }
}
